﻿Shader "Running/Wall"
{
	Properties
	{
		decal1Map("decal1Map", 2D) = "white" {}
		decal2Map("decal2Map", 2D) = "white" {}
		cutoutMap("cutoutMap", 2D) = "white" {}

		_ambientLightColor("_ambientLightColor", Color) = (0.258, 0.316, 0.324, 0.445)
		_shadowMap("shadowMap", 2D) = "white" {}

		inverseShadowmapSize("inverseShadowmapSize", Float) = 0.000976
		fixedDepthBias("fixedDepthBias", Float) = 0.0016
		gradientClamp("gradientClamp", Float) = 0.0098
		gradientScaleBias("gradientScaleBias", Float) = 1

		shadowColor("shadowColor", Color) = (1, 1, 1, 1)
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" }
		LOD 100

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			
			#include "UnityCG.cginc"
			#include "Lighting.cginc"
			#include "tools.cginc"


			struct appdata
			{
				float4 vertex : POSITION;
				float4 normal : NORMAL;
				float4 uv1 : TEXCOORD0;
				float4 uv2 : TEXCOORD1;
				float4 uv3 : TEXCOORD2;
				float4 cutoutBlend : TEXCOORD3;
				float4 surfaceColor : COLOR;

			};

			struct v2f
			{
				float4 pos : SV_POSITION;
				float4 color : COLOR;
				float4 shadowUV : TEXCOORD0;
				float4 decal1UV : TEXCOORD1;
				float4 decal2UV : TEXCOORD2;
				float4 diffuseLightColor : TEXCOORD3;
				float4 cutoutUV : TEXCOORD4;
				float4 cutoutBlend : TEXCOORD5;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			
			v2f vert (appdata v)
			{
				v2f o;
				float4 worldPos = mul(unity_ObjectToWorld, v.vertex);
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				o.color = v.surfaceColor;
				o.diffuseLightColor = lightning(_WorldSpaceLightPos0, _LightColor0, worldPos, unity_WorldToObject, v.normal);
				o.shadowUV = mul(texViewProj, worldPos);
				o.decal1UV = v.uv1;
				o.decal2UV = v.uv2;
				o.cutoutUV = v.uv3;
				o.cutoutBlend = v.cutoutBlend;
				return o;
			}
			
			uniform float4 _ambientLightColor;
			sampler2D _shadowMap;
			uniform float fixedDepthBias;
			uniform float gradientClamp;
			uniform float gradientScaleBias;
			uniform float4 shadowColor;

			sampler2D decal1Map;
			sampler2D decal2Map;
			sampler2D cutoutMap;

			fixed4 frag (v2f i) : SV_Target
			{
				float4 decal1 = tex2D(decal1Map, i.decal1UV);
				float4 decal2 = tex2D(decal2Map, i.decal2UV);
				float4 cutout = tex2D(cutoutMap, i.cutoutUV);

				cutout.r =
					i.cutoutBlend.r * cutout.r +
					i.cutoutBlend.g * cutout.g +
					i.cutoutBlend.b * cutout.b +
					i.cutoutBlend.a * cutout.a;
				
				float4 mix;
				mix.rgb = decal1.a * decal1.rgb + (1.0 - decal1.a) * i.color.rgb;
				mix.rgb = cutout.r * mix.rgb + (1.0 - cutout.r) * i.color.rgb;
				mix.rgb = decal2.a * decal2.rgb + (1.0 - decal2.a) * mix.rgb;
				mix.a = 1.0;

				float4 result;
				result = mix * _ambientLightColor +
					mix * i.diffuseLightColor *
					inShadow(i.pos, i.shadowUV, _shadowMap, inverseShadowmapSize, fixedDepthBias, gradientClamp, gradientScaleBias, shadowColor.a);

				return result;
			}
			ENDCG
		}
	}
}
